package com.pactera.demo.security.handler;

import com.pactera.demo.common.dto.ResponseResult;
import com.pactera.demo.common.enums.StatusCodeEnum;
import com.pactera.demo.common.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author chang.zhou
 * @since 2020/03/01 22:11
 */
@Slf4j
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.info("SimpleAuthenticationEntryPoint -> AuthenticationException -> {}", authException.getClass().getName());

        if(authException instanceof InsufficientAuthenticationException){
            ResponseUtil.jsonWriter(response, ResponseResult.fail(StatusCodeEnum.INSUFFICIENT_AUTHENTICATION));
        }else{
            ResponseUtil.jsonWriter(response, ResponseResult.fail(StatusCodeEnum.AUTHENTICATION_FAILED));
        }
    }
}
